﻿using System.IO;
using System.Net.Mail;
using System.Net.Mime;
using System.ServiceModel;
using System.Text;

namespace CodeBadger.GasMileage.Web
{
    [ServiceContract]
    public interface IExportService
    {
        [OperationContract]
        void EmailData(string token, string email, string data);
    }
    
    public class ExportService : IExportService
    {
        public void EmailData(string token, string email, string data)
        {
            if (token != Properties.Settings.Default.Token) return;
            data = data.Replace("utf-16", "utf-8");
            
            if (!data.StartsWith("<?xml version=\"1.0\" encoding=\"utf-8\"?>")) return;
            if (!data.Contains("ArrayOfNotebookEntry")) return;

            using (var stream = new MemoryStream(Encoding.Default.GetBytes(data)))
            {
                var message = new MailMessage(
                    "mileage@codebadger.com",
                    email,
                    "Your Gas Mileage Data",
                    Properties.Settings.Default.EmailMessage);

                stream.Position = 0;
                var attachment = new Attachment(stream, new ContentType("text/xml")) { Name = "mileage.xml" };
                message.Attachments.Add(attachment);

                var client = new SmtpClient("localhost");
                client.Send(message);
            }
        }
    }
}
